<template>
  <div style="max-width: 1000px; margin: 40px auto;">
    <el-card shadow="hover">
      <template #header>
        <span style="font-size: 20px; font-weight: bold;">我的订单</span>
        <el-select v-model="statusFilter" placeholder="全部状态" style="float: right; width: 160px;" @change="fetchOrders">
          <el-option label="全部状态" value="" />
          <el-option label="待付款" value="UNPAID" />
          <el-option label="已付款" value="PAID" />
          <el-option label="已发货" value="SHIPPED" />
          <el-option label="已完成" value="COMPLETED" />
          <el-option label="已取消" value="CANCELLED" />
        </el-select>
      </template>
      <div style="margin-bottom: 16px;">
        <el-button type="danger" :disabled="!canBatchDelete" @click="handleBatchDelete">批量删除</el-button>
      </div>
      <el-table :data="filteredOrders" style="width: 100%;" border @selection-change="handleSelectionChange" ref="orderTable">
        <el-table-column type="selection" width="50" :selectable="row => canDelete(row)" />
        <el-table-column prop="orderSn" label="订单号" width="220" />
        <el-table-column prop="createTime" label="下单时间" width="180" />
        <el-table-column prop="totalAmount" label="金额" width="120">
          <template #default="scope">
            ￥{{ scope.row.totalAmount && scope.row.totalAmount.toFixed ? scope.row.totalAmount.toFixed(2) : scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            {{ statusText(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button size="small" @click="goDetail(scope.row.orderId)">详情</el-button>
            <el-button v-if="canDelete(scope.row)" size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!orders.length" style="text-align: center; color: #bbb; padding: 40px;">暂无订单</div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const router = useRouter()
const orders = ref([])
const statusFilter = ref('')
const selectedOrders = ref([])
const orderTable = ref(null)

const fetchOrders = async () => {
  const res = await request.get('/api/order/list')
  if (res.success) {
    orders.value = res.data || []
  }
}

const filteredOrders = computed(() => {
  if (!statusFilter.value) return orders.value
  return orders.value.filter(o => o.status === statusFilter.value)
})

function statusText(status) {
  switch (status) {
    case 'UNPAID': return '待付款'
    case 'PAID': return '已付款'
    case 'SHIPPED': return '已发货'
    case 'COMPLETED': return '已完成'
    case 'CANCELLED': return '已取消'
    default: return status
  }
}

function goDetail(orderId) {
  router.push({ name: 'UserOrderDetail', params: { orderId } })
}

function canDelete(order) {
  return order.status === 'CANCELLED' || order.status === 'COMPLETED'
}

function handleSelectionChange(selection) {
  selectedOrders.value = selection
}

const canBatchDelete = computed(() => selectedOrders.value.length > 0)

function handleDelete(order) {
  ElMessageBox.confirm('确定要删除该订单吗？删除后无法恢复！', '提示', { type: 'warning' })
    .then(async () => {
      const res = await request.post(`/api/order/${order.orderId}/delete`)
      if (res.success) {
        ElMessage.success('删除成功')
        fetchOrders()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    })
}

function handleBatchDelete() {
  ElMessageBox.confirm(`确定要删除选中的${selectedOrders.value.length}个订单吗？删除后无法恢复！`, '批量删除', { type: 'warning' })
    .then(async () => {
      let successCount = 0
      for (const order of selectedOrders.value) {
        const res = await request.post(`/api/order/${order.orderId}/delete`)
        if (res.success) successCount++
      }
      ElMessage.success(`成功删除${successCount}个订单`)
      fetchOrders()
    })
}

onMounted(fetchOrders)
</script> 